package com.avic.modules.backup4Dameng.config;

import com.avic.modules.backup4Dameng.DmpBackup;
import com.avic.modules.backup4Dameng.remote.ScpCopyExecute;
import com.avic.modules.quartz.domain.QuartzJob;
import com.avic.modules.quartz.service.QuartzJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
//@Configuration
public class BackupConfig {


    private final QuartzJobService quartzJobService;
    private final ScpCopyExecute scpCopyExecute;

    @Value("${dm.dexp.path}")
    private  String dexpPath;

    @Value("${dm.dexp.URL}")
    private  String dexpURL;

    @Value("${dm.dexp.expDir}")
    private  String dexpDirectory;

    @Value("${dm.dexp.winAdmin}")
    private  String winAdmin;

    @Value("${dm.dexp.winAdminPass}")
    private  String winAdminPass;

    @Value("${dm.dexp.addr}")
    private  String addr;

    public BackupConfig(QuartzJobService quartzJobService, ScpCopyExecute scpCopyExecute) {
        this.quartzJobService = quartzJobService;
        this.scpCopyExecute = scpCopyExecute;
    }

    @Bean
    public void doBackupJobDefault(){

        List<QuartzJob> quartzJobList = quartzJobService.checkBackupJob();
        if (quartzJobList.size() == 0){
            QuartzJob quartzJob = new QuartzJob();
            quartzJob.setBeanName("dmpBackupTask");
            quartzJob.setMethodName("runDMDexp");
            quartzJob.setRemark("daily backup job,don't delete");
            quartzJob.setJobName("doFixedTimeBackupTask 数据库定时备份 Default");
            quartzJob.setIsPause(false);
            /**
             * 默认每天 18 点备份一次
             */
            quartzJob.setCronExpression("0 0 18 * * ?");
            if (quartzJobService.save(quartzJob)) {
                log.info("创建定时备份任务入库 ：[ quartz job name = {} ]", quartzJob.getJobName());
            }else{
                throw new RuntimeException("默认创建备份任务失败");
            }
        }else{
            QuartzJob quartzJob = quartzJobList.get(0);
            if(quartzJob.getIsPause()){
                quartzJob.setIsPause(false);
                quartzJobService.updateById(quartzJob);
            }
            log.info("【------------定时备份任务正常------------】");
        }
    }

    @Bean
    @PostConstruct
    public DmpBackup  dmpBackup(){
        DmpBackup dmpBackup = new DmpBackup(scpCopyExecute);
        dmpBackup.init(dexpPath,dexpURL,dexpDirectory, winAdmin, winAdminPass,addr);
        return dmpBackup;
    }
}
